<template>
  <div class="cart">
    <div class="cart-header">
      <strong>购物车</strong> 
      <div class="cart-checkout" @click="checkOut">结算</div>
      <div class="cart-totalPrice">合计：{{ totalPrice | formatPrice }}</div>


    </div>
    <div class="cart-content">
      <CartItem v-for="n in addedInfos" :key="n.id" :cartItem="n"/>
    </div>
  </div>
</template>

<script>
  import { mapGetters, mapActions } from 'vuex'
  import CartItem from './CartItem.vue'
  export default {
    components: {
      CartItem
    },
    computed: {
      totalPrice: function () {
        let sum = 0
        let added = this.$store.getters.productsInCart
        added.forEach(function (item) {
          let p = this.$store.getters.getProductById(item.id)
          if (p) {
            sum += item.quantity * p.price
          }
        },
        // 注意此为forEach处传入this，在回调函数执行时作为回调函数的this来用
        this)

        return sum
      },
      ...mapGetters({
        addedInfos: 'productsInCart'
      })
    },
    methods: {
      ...mapActions([
        'checkOut'
      ])
    }
  }
</script>

<style scoped>
.cart {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
}


.cart-header {  
  position: absolute;
  top: 0;
  height: 30px;
  width: 100%;
  background-color: #ddd;
  padding: 5px 10px;
}

.cart-content {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  margin-top: 30px;
  overflow-y: auto; 
}

.cart-checkout {  
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  width: 50px;
  
  background-color: red;
  color: #fff;
  padding: 5px 10px;
  cursor: pointer;
}

.cart-totalPrice {
  position: absolute;
  top: 0;
  right: 50px;
  bottom: 0;
  
  padding: 5px 10px;
}

@media (min-width: 768px) {
  .cart {
    margin-bottom: 50px;
  }
  
  .cart-content {
    padding: 40px 80px;
  }
}


@media (max-width: 767px) {
  .cart {
    margin-bottom: 80px;
  }

  .cart-content {
    padding: 30px 40px;
  }
}

</style>